package i.i.myapplication;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import i.i.myapplication.controller.NewsAdapter;
import i.i.myapplication.model.NewsResponse;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class NewsFragment extends Fragment {
    private static final String TAG = "NewsFragment";
    private RecyclerView recyclerView;
    private NewsAdapter adapter;
    private EditText etSearch;
    private Button btnSearch;
    private SwipeRefreshLayout swipeRefreshLayout;

    private List<NewsResponse.Result.NewsItem> allNewsItems = new ArrayList<>();
    private List<NewsResponse.Result.NewsItem> filteredNewsItems = new ArrayList<>();

    private OkHttpClient client = new OkHttpClient();
    private Handler mainHandler = new Handler(Looper.getMainLooper());
    private Gson gson = new Gson();

//    private static final String API_KEY = "e5461cbb712f142831801bfd2ba5529d";
    private static final String API_KEY = "e5461cbb712f142831801bfd2ba5529d";
    private static final String API_URL = "https://v.juhe.cn/toutiao/index?key=" + API_KEY;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_news, container, false);

        etSearch = view.findViewById(R.id.etSearch);
        btnSearch = view.findViewById(R.id.btnSearch);
        swipeRefreshLayout = view.findViewById(R.id.swipeRefreshLayout);
        recyclerView = view.findViewById(R.id.rv_news);

        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        adapter = new NewsAdapter(getContext(), filteredNewsItems);
        recyclerView.setAdapter(adapter);

        btnSearch.setOnClickListener(v -> {
            String keyword = etSearch.getText().toString().trim();
            filterNewsByTitle(keyword);
        });

        swipeRefreshLayout.setOnRefreshListener(this::fetchNewsFromNetwork);

        // 首次加载数据
        swipeRefreshLayout.setRefreshing(true);
        fetchNewsFromNetwork();

        return view;
    }

    private void fetchNewsFromNetwork() {
        Request request = new Request.Builder()
                .url(API_URL)
                .build();
        Log.d(TAG, "请求URL: " + API_URL);  // 打印
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                mainHandler.post(() -> {
                    swipeRefreshLayout.setRefreshing(false);
                    Toast.makeText(getContext(), "网络请求失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String json = response.body().string();
                try {
                    NewsResponse newsResponse = gson.fromJson(json, NewsResponse.class);
                    if (newsResponse != null && newsResponse.getResult() != null) {
                        List<NewsResponse.Result.NewsItem> newsList = newsResponse.getResult().getData();
                        mainHandler.post(() -> {
                            allNewsItems.clear();
                            allNewsItems.addAll(newsList);
                            // 过滤显示，保持搜索关键词
                            String keyword = etSearch.getText().toString().trim();
                            filterNewsByTitle(keyword);
                            swipeRefreshLayout.setRefreshing(false);
                        });
                    } else {
                        mainHandler.post(() -> {
                            swipeRefreshLayout.setRefreshing(false);
                            Toast.makeText(getContext(), "数据解析错误", Toast.LENGTH_SHORT).show();
                        });
                    }
                } catch (JsonSyntaxException e) {
                    mainHandler.post(() -> {
                        swipeRefreshLayout.setRefreshing(false);
                        Toast.makeText(getContext(), "数据格式错误", Toast.LENGTH_SHORT).show();
                    });
                    Log.e("NewsFragment", "JSON解析异常", e);
                }
            }
        });
    }

    // 按标题关键字过滤新闻列表
    private void filterNewsByTitle(String keyword) {
        filteredNewsItems.clear();

        if (TextUtils.isEmpty(keyword)) {
            filteredNewsItems.addAll(allNewsItems);
        } else {
            for (NewsResponse.Result.NewsItem item : allNewsItems) {
                if (item.getTitle() != null && item.getTitle().toLowerCase().contains(keyword.toLowerCase())) {
                    filteredNewsItems.add(item);
                }
            }
        }

        adapter.notifyDataSetChanged();
    }
}
